package com.spooky.sync.note;

import java.util.LinkedList;
import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.database.DataSetObserver;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.InputFilter;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.spooky.sync.R;
import com.spooky.sync.note.model.TagStatus;
import com.spooky.sync.persistence.dao.TagDAO;
import com.spooky.sync.persistence.dao.TagDAOBean;
import com.spooky.sync.persistence.db.UpdateSql;
import com.spooky.sync.persistence.entity.Tag;

public class TagHandlerActivity extends ListActivity {
	private static final String TAG = "TagHandlerActivity";
	protected EditText mTagText;
	private TagDAO mTagDAO;
	// GUI
	private AlertDialog mAlertDialog = null;
	protected Tag mTag = null;
	private TagStatus mTagStatus;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.tag_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.createTagMenuItem: {
			startCreateDialog();
			return true;
		}
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		// v = findViewById(android.R.layout.simple_spinner_dropdown_item);
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.editor_menu, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		switch (item.getItemId()) {
		case R.id.editorSaveItem: {
			Log.d(TAG, "editorSaveItem:" + info.id);
			// editNote(info.id);
			return true;
		}
		case R.id.editorTitleItem: {
			Log.d(TAG, "editorSaveItem:" + info.id);
			// deleteNote(info.id);
			return true;
		}
		default:
			return super.onContextItemSelected(item);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mTagDAO = new TagDAOBean(TagHandlerActivity.this);
		mTagStatus = TagStatus.getInstance();
		mTag = Tag.getEditorInstance();
	}

	@Override
	protected void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mTagStatus.isDialogShowing()) {
			startCreateDialog();
		}
		new DatabaseRequest().execute();
	}

	@Override
	protected void onPause() {
		super.onPause();
		onPauseCreateDialog();
		mTagDAO.close();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		UpdateSql.onDestroy();
	}

	private void startCreateDialog() {
		if (mAlertDialog == null) {
			mAlertDialog = new CreateDialog().create();
		}
		if (!mAlertDialog.isShowing()) {
			mAlertDialog.show();
		}
	}

	private void onPauseCreateDialog() {
		if (mAlertDialog != null) {
			if (mAlertDialog.isShowing()) {
				mAlertDialog.dismiss();
				mTag.setName(mTagText.getText().toString());
			}
		}
	}

	private class DatabaseRequest extends AsyncTask<String, Integer, List<Tag>> {
		private TagDAO mTagDAO;

		@Override
		protected List<Tag> doInBackground(String... arg0) {
			try {
				return mTagDAO.list(1, 1);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return new LinkedList<Tag>();
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
			mTagDAO.close();
		}

		@Override
		protected void onPostExecute(List<Tag> result) {
			super.onPostExecute(result);
			mTagDAO.close();
			TagHandlerActivity.this.setListAdapter(new CustomAdapter(result));
			getListView().setOnCreateContextMenuListener(TagHandlerActivity.this);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mTagDAO = new TagDAOBean(TagHandlerActivity.this);
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

		private class CustomAdapter implements ListAdapter {
			private List<Tag> mResult;

			public CustomAdapter(List<Tag> result) {
				mResult = result;
			}// TagHandlerActivity.this, android.R.layout.simple_list_item_1,

			@Override
			public int getCount() {
				return mResult.size();
			}

			@Override
			public Object getItem(int pos) {
				return mResult.get(pos);
			}

			@Override
			public long getItemId(int position) {
				return mResult.get(position).getId();
			}

			@Override
			public int getItemViewType(int position) {
				return 0;
			}

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				// TableRow row = new TableRow(TagHandlerActivity.this);
				final TextView name = new TextView(TagHandlerActivity.this, null, android.R.layout.simple_spinner_dropdown_item);
				name.setText(mResult.get(position).getName());
				name.setLongClickable(true);
				/*
				 * name.setOnClickListener(new View.OnClickListener() {
				 * 
				 * @Override public void onClick(View v) {
				 * name.showContextMenu(); Log.d(TAG, "setOnClickListener"); }
				 * });
				 */
				return name;
			}

			@Override
			public int getViewTypeCount() {
				return 1;
			}

			@Override
			public boolean hasStableIds() {
				return true;
			}

			@Override
			public boolean isEmpty() {
				return mResult.isEmpty();
			}

			@Override
			public void registerDataSetObserver(DataSetObserver observer) {
			}

			@Override
			public void unregisterDataSetObserver(DataSetObserver observer) {
			}

			@Override
			public boolean areAllItemsEnabled() {
				return true;
			}

			@Override
			public boolean isEnabled(int position) {
				return true;
			}
		}
	}

	private class CreateDialog extends AlertDialog.Builder {
		public CreateDialog() {
			super(TagHandlerActivity.this);
			mTagStatus.setDialogShowing(true);
			setTitle(R.string.tag_create_dialog_title);
			setCancelable(false);
			mTagText = new EditText(TagHandlerActivity.this);
			mTagText.setText(mTag.getName() == null ? "" : mTag.getName());
			mTagText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(Tag.MAX_NAME_LENGTH) });
			setView(mTagText);
			setPositiveButton("Create", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					mTagStatus.setDialogShowing(false);
					mTag.setName(mTagText.getText().toString());
					new SaveNote().save();
				}
			});
			setNegativeButton("Back", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					mTagStatus.setDialogShowing(false);
					dialog.cancel();
				}
			});
		}

		private class SaveNote {
			public void save() {
				assemble();
				if (verify()) {
					if (saveAction()) {
						back();
					}
				}
			}

			private boolean verify() {
				if (mTag.getName() == null || mTag.getName().length() <= Tag.MIN_NAME_LENGTH) {
					Toast.makeText(TagHandlerActivity.this, R.string.tag_verify_tag_short, Toast.LENGTH_LONG).show();
					return false;
				}
				return true;
			}

			private void assemble() {
			}

			private boolean saveAction() {
				try {
					if (mTag.getId() == null) {
						mTagDAO.create(mTag);
						Toast.makeText(TagHandlerActivity.this, R.string.tag_verify_save, Toast.LENGTH_LONG).show();
					} else {
						mTagDAO.update(mTag);
						Toast.makeText(TagHandlerActivity.this, R.string.tag_verify_update, Toast.LENGTH_LONG).show();
					}
					Tag.clearEditInstance();
					TagStatus.clearEditInstance();
					return true;
				} catch (Exception e) {
					e.printStackTrace();
					Toast.makeText(TagHandlerActivity.this, R.string.tag_unknown_error, Toast.LENGTH_LONG).show();
				}
				return false;
			}

			private void back() {
				TagHandlerActivity.this.finish();
			}
		}
	}
}
